﻿function AzureOnlineAccountsViewModel(context) {

    var accountName = context.accounts.accountName;
    var accounts = context.accounts.accounts;
    var account = context.accounts.account;
    var details = new AzureOnlineAccountDetailsView(context);
    var settings = context.settings;

    var deleteDetails = (function () {

        var dispatcher = $({});

        var accountToDelete = null;

        function init(acc) {
            accountToDelete = acc;
        }
        
        function remove() {
            accounts.remove(accountToDelete);
            if (account() == accountToDelete) {
                account(null);
            }
            dispatcher.trigger('success');
        }

        function addOnSuccess(handler) {
            dispatcher.bind('success', handler);
        };

        return {
            init: init,
            account: account,
            remove: remove,
            addOnSuccess: addOnSuccess
        };

    })();
    
    function getInfo() {
        var res = [];
        var accs = accounts();
        for (var i = 0; i < accs.length; i++) {
            var acc = accs[i];
            res.push({
                name: acc.storageName(),
                key: acc.storageKey(),
                devStorage: acc.devStorage()
            });
        }
        return res;
    }

    function store() {
        var info = getInfo();
        settings.setObject('storages', info);
        settings.setItem('storages.current', accountName());
    }

    function load() {
        var list = settings.getObject('storages');
        if (list) {
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                var acc = new AzureOnlineAccount();
                acc.storageName(item.name);
                acc.storageKey(item.key);
                acc.devStorage(item.devStorage);
                accounts.push(acc);
            }
            accountName(settings.getItem('storages.current'));
        }
    }

    function select(acc) {
        account(acc);
        store();
    }

    load();

    ko.computed(function () {
        var accs = accounts();
        var acc = account();
        if (!acc && accs.length > 0) {
            acc = accs[0];
            accountName(acc.storageName());
            store();
        }
    }).extend({ throttle: 1 });


    details.addOnSuccess(store);
    deleteDetails.addOnSuccess(store);

    this.account = account;
    this.accountName = accountName;
    this.accounts = accounts;
    this.details = details;
    this.deleteDetails = deleteDetails;
    this.select = select;
}
